#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <memory>
#include "Mutex.hpp"
#include "Cond.hpp"
#include "Thread.hpp"
#include "Log.hpp"

namespace ThreadPoolModule
{
    using namespace MutexModule;
    using namespace CondModule;
    using namespace ThreadModule;
    using namespace LogModule;

    using thread_t = std::shared_ptr<Thread>;
    const static int defaultnum = 15;

    template <class T>
    class ThreadPool
    {
    private:
        bool IsEmpty() { return _taskq.empty(); }

        void HandlerTask(std::string name)
        {
            LOG(LogLevel::INFO) << "线程: " << name << ", 进入HandlerTask执行逻辑";
            while (true)
            {
                // 1. 拿任务: 访问共享资源, 需要加锁
                T task;
                {
                    LockGuard lockguard(_mutex);
                    while (IsEmpty() && _isrunning) // while替代if: 防止伪唤醒
                    {
                        _wait_num++;
                        _cond.Wait(_mutex); // 没任务时: 线程在条件变量上阻塞等待
                        _wait_num--;
                    }
                    // 2. 任务队列不为空 && 线程池退出
                    if (IsEmpty() && !_isrunning)
                        break;

                    task = _taskq.front();
                    _taskq.pop();
                }

                // 3. 处理任务: 并发处理, 不需要持有锁
                task();
            }
            LOG(LogLevel::INFO) << "线程: " << name << ", 退出";
        }

        ThreadPool(int num = defaultnum)
            : _num(num), _wait_num(0), _isrunning(false)
        {
            for (int i = 0; i < _num; i++)
            {
                // 在类中: bind类的公有方法, 需要取地址 + 传入this指针
                // 在类外: bind类的公有方法, 需要取地址 + 传入类的匿名对象
                _threads.push_back(std::make_shared<Thread>(std::bind(&ThreadPool::HandlerTask, this, std::placeholders::_1))); // push_back()会调用移动构造
                LOG(LogLevel::INFO) << "构建线程" << _threads.back()->Name() << "对象...成功";
            }
        }

        ThreadPool<T>(const ThreadPool<T> &) = delete;
        ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;

    public:
        ~ThreadPool() {}

        // 获取单例对象
        static ThreadPool<T> *GetInstance()
        {
            // 若单例为空: 需要加锁创建单例对象
            if(instance == nullptr)
            {
                LockGuard lockguard(_lock);
                if(instance == nullptr)
                {
                    LOG(LogLevel::INFO) << "单例首次被执行, 需要加载对象...";
                    instance = new ThreadPool<T>();
                    instance->Start();
                }
            }
            // 若单例不为空: 直接返回单例对象
            return instance;
        }

        void Equeue(T in)
        {
            LockGuard lockguard(_mutex);
            if (!_isrunning) return;
            _taskq.push(in);
            if (_wait_num > 0)
            {
                _cond.Signal(); // 唤醒线程
            }
        }

        void Start()
        {
            if (_isrunning) return;
            _isrunning = true;
            for (auto &thread_ptr : _threads)
            {
                thread_ptr->Start();
                LOG(LogLevel::INFO) << "启动线程" << thread_ptr->Name() << "...成功";
            }
        }

        void Stop()
        {
            LockGuard lockguard(_mutex);
            if (_isrunning)
            {
                // 1. 不能再新增任务了
                _isrunning = false;

                // 2. 让线程自己退出(唤醒所有的线程) && 历史任务被执行完
                if (_wait_num > 0)
                {
                    _cond.Broadcast();
                }
            }
        }

        void Wait()
        {
            for (auto &thread_ptr : _threads)
            {
                thread_ptr->Join();
                LOG(LogLevel::INFO) << "回收线程" << thread_ptr->Name() << "...成功";
            }
        }

    private:
        int _num;                       // 线程的个数
        std::vector<thread_t> _threads; // 线程池
        std::queue<T> _taskq;           // 共享资源: 任务队列
        int _wait_num;                  // 等待的线程数目
        bool _isrunning;                // 线程池是否运行

        Mutex _mutex; // 锁
        Cond _cond;   // 条件变量

        static ThreadPool<T> *instance; // 单例对象
        static Mutex _lock;             // 用来保护单例
    };

    // 静态成员: 类内声明, 类外定义
    template<class T>
    ThreadPool<T> *ThreadPool<T>::instance = nullptr;
    
    template<class T>
    Mutex ThreadPool<T>::_lock;
}